<template>
	<view class="preview">
		<view class="loading" v-if="currentIndex === -1">
			<uni-load-more status="loading"></uni-load-more>
		</view>
		<view class="content" @click="onChangeMaskstate">
			<swiper :indicator-dots="true" circular :current="currentIndex" @change="changeCurrent">
				<swiper-item v-for="(item,index) in classList" :key="item._id">
					<image v-if="readedArr.includes(index)" :src="item.picurl" mode="aspectFill"></image>
				</swiper-item>
			</swiper>
			<!-- {{readedArr}} -->
			<view class="mask" v-if="maskstate">
				<view class="back" :style="{top:getStatusBarHeight() + 'px'}" @click="onGoBack">
					<uni-icons type="back" color="#fff" size="20"></uni-icons>
				</view>
				<view class="count">
					{{currentIndex + 1}} / {{classList.length}}
				</view>
				<view class="time">
					<uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
				</view>
				<view class="date">
					<uni-dateformat :date="Date.now()" format="MM月dd日"></uni-dateformat>
				</view>
				<view class="footer">
					<view class="box" @click="onOpenInfo">
						<uni-icons type="info" size="25"></uni-icons>
						<view class="text">
							信息
						</view>
					</view>
					<view class="box" @click="onOpenScore">
						<uni-icons type="star" size="25"></uni-icons>
						<view class="text">
							评分
						</view>
					</view>
					<view class="box" @click="onDownload">
						<uni-icons type="download" size="25"></uni-icons>
						<view class="text">
							下载
						</view>
					</view>
				</view>
			</view>

			<uni-popup ref="infopopup" type="bottom">
				<view class="infopopup">
					<view class="infoheader">
						<view></view>
						<view class="title">
							壁纸信息
						</view>
						<view class="close" @click="onCloseInfo">
							<uni-icons type="closeempty" size="18" color="$text-font-color-3"></uni-icons>
						</view>
					</view>
					<scroll-view scroll-y>
						<view class="content" v-if="currentInfo">
							<view class="row">
								<view class="label">壁纸ID：</view>
								<text class="value" selectable>{{currentInfo._id}}</text>
							</view>
							<!-- <view class="row">
								<view class="label">分类：</view>
								<text class="value hightClass" selectable>美女</text>
							</view> -->
							<view class="row">
								<view class="label">发布者：</view>
								<text class="value" selectable>{{currentInfo.nickname}}</text>
							</view>
							<view class="row">
								<view class="label">评分：</view>
								<view class="value rate">
									<uni-rate :value="currentInfo.score" readonly size="16"></uni-rate>
									<text class="score">{{currentInfo.score}}分</text>
								</view>
							</view>
							<view class="row">
								<view class="label">摘要：</view>
								<view class="value">
									{{currentInfo.description}}
								</view>
							</view>
							<view class="row">
								<view class="label">标签：</view>
								<view class="value tabs">
									<view class="tab" v-for="item in currentInfo.tabs" :key="item">{{item}}</view>
								</view>
							</view>
							<view class="copyright">
								声明：本图片来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝壁纸ID举报至平台，邮箱513894357@qq.com，管理将删除侵权壁纸，维护您的权益。
							</view>
						</view>
					</scroll-view>
				</view>
			</uni-popup>
			<uni-popup ref="scorepopup" type="center" :is-mask-click="false">
				<view class="scorePopup">
					<view class="infoheader">
						<view></view>
						<view class="title">
							{{ifRated ? "已经评分过了~" : "壁纸评分"}}
						</view>
						<view class="close" @click="onCloseScore">
							<uni-icons type="closeempty" size="18" color="$text-font-color-3"></uni-icons>
						</view>
					</view>
					<view class="content">
						<uni-rate v-model="userScore" allowHalf size="20"></uni-rate>
						<text class="score">{{userScore}}分</text>
					</view>
					<view class="footer">
						<button :disabled="!userScore || ifRated" type="default" size="mini" plain
							@click="onRate">确定评分</button>
					</view>
				</view>
			</uni-popup>
		</view>
	</view>
</template>

<script setup>
	import {
		getStatusBarHeight,
	} from '@/utils/system.js';
	import {
		setScoreAPI,
		updateDownload
	} from '@/api/api.js'
	import {
		ref
	} from 'vue';
	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from "@dcloudio/uni-app"
	/* ========常用变量================= */
	const classList = ref([]);
	const currentIndex = ref(-1);
	const readedArr = ref([]);
	/* info弹窗具体信息 */
	const currentInfo = ref(null);
	const changeCurrentInfo = () => {
		currentInfo.value = classList.value[currentIndex.value];
		console.log("currentInfo.value", currentInfo.value);
	}
	/* ========awiper================= */
	/* 从缓存中获取预览数据 */
	const storageClassList = uni.getStorageSync('storageclassList') || [];
	console.log("storageClassList", storageClassList);
	classList.value = storageClassList._value.map(item => {
		// console.log(item)
		return {
			...item,
			picurl: item.smallPicurl.replace("_small.webp", ".jpg")
		}
	})
	console.log("classList.value", classList.value);
	/* 首次加载的优化*/
	function readedArrFun() {
		/* 重点：首次加载的优化 -- 已读数组 */
		readedArr.value.push(
			currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1
		)
		/* 重点：首次加载的优化 -- 已读数组的元素唯一性 */
		readedArr.value = [...new Set(readedArr.value)];
	}
	/* 获取查询参数 和 获取当前预览图的位置 */
	/* 重点：首次加载的优化 -- v-if */
	onLoad((e) => {
		console.log("e.id", e.id)
		currentIndex.value = classList.value.findIndex((item) => {
			console.log("item._id", item._id);
			return item._id === e.id;
		});
		readedArrFun();
		changeCurrentInfo();
	})
	/* swiper当前值改变 */
	const changeCurrent = (e) => {
		console.log("awiper的change事件中的e", e);
		currentIndex.value = e.detail.current;
		readedArrFun();
		changeCurrentInfo();
	}
	/* ========mask================ */
	/* 遮罩层 */
	const maskstate = ref(false)

	function onChangeMaskstate() {
		maskstate.value = !maskstate.value
	}
	/* 返回 */
	function onGoBack() {
		uni.navigateBack()
	}
	/* info弹窗 */
	const infopopup = ref()

	function onOpenInfo(e) {
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
		console.log(infopopup.value)
		infopopup.value.open();
	}

	function onCloseInfo(e) {
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
		console.log(infopopup.value)
		infopopup.value.close();
	}
	/* 评分弹窗 */
	const scorepopup = ref()
	const userScore = ref(0)
	const ifRated = ref(false)

	function onOpenScore(e) {
		console.log("OpenScore:e", e);
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
		if (currentInfo.value.userScore) {
			ifRated.value = true;
			userScore.value = currentInfo.value.userScore;
		} else {
			userScore.value = 0;
		}
		console.log(scorepopup.value)
		scorepopup.value.open();
	}

	function onCloseScore(e) {
		console.log("CloseScore:e", e);
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
		ifRated.value = false;
		console.log(scorepopup.value)
		scorepopup.value.close();
	}
	async function onRate() {
		let {
			classid,
			_id: wallId
		} = currentInfo.value;

		let res = await setScoreAPI({
			classid,
			wallId,
			userScore: userScore.value
		})
		if (res.errCode === 0) {
			uni.showToast({
				title: "评分成功",
				icon: "none"
			})
			/* 更新缓存，存储用户评分状态 */
			classList.value[currentIndex.value].userScore = userScore.value;
			uni.setStorageSync("storageclassList", classList);
			// uni.setStorageSync("storageclassList",classList);z
			onCloseScore();
		}
		userScore.value = 0;
		console.log("评分userScore,", userScore.value);
		console.log("评分res", res);
	}
	/* 下载图片 */
	const onDownload = async (e) => {
		console.log("下载图片")
		if (e && e.stopPropagation) {
			e.stopPropagation();
		}
		// #ifdef H5
		uni.showModal({
			content: "请长按保存图片",
			showCancel: false
		})
		// #endif
		// #ifndef H5
		try {
			uni.showLoading({
				title: "下载中...",
				mask: true
			})
			let {
				classid,
				_id: wallId
			} = currentInfo.value;
			let res = await updateDownload({
				classid: wallId
			})
			if (res.errCode != 0) return;
			console.log("记录下载记录 ", res)

			uni.getImageInfo({
				src: currentInfo.value.picurl,
				success(res) {
					console.log("getImageInfo res", res)
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success(res) {
							console.log("saveImage ress", res)
							uni.showToast({
								title: "保存成功，请前往相册查看",
								icon: "none"
							})
						},
						fail(err) {
							console.log("saveImage errr", err);
							if (err.errMsg === 'saveImageToPhotosAlbum:fail cancel') {
								uni.showToast({
									title: "保存失败，请点击重新下载",
									icon: "none"
								})
								return;
							}
							uni.showModal({
								title: "提示",
								content: "需要授权保存相册",
								success(res) {
									if (res.confirm) {
										console.log("确认授权了1", res)
										uni.openSetting({
											success(setting) {
												console.log("确认授权了2 setting",
													setting)
												if (setting.authSetting[
														'scope.writePhotosAlbum'
														]) {
													uni.showToast({
														title: "授权成功",
														icon: "none"
													})
												} else {
													uni.showToast({
														title: "获取授权失败",
														icon: "none"
													})
												}
											}
										})
									}
								}
							})
						},
						complete() {
							uni.hideLoading();
						}
					})
				},
				complete() {
					uni.hideLoading();
				}
			})

		} catch (error) {
			//TODO handle the exception
			console.log("error",error);
			uni.hideLoading();
		}

		// #endif
	}
</script>

<style lang="scss" scoped>
	.preview {
		.content {
			width: 750rpx;
			height: 100vh;
			position: relative;

			swiper {
				width: 100%;
				height: 100%;

				swiper-item {
					width: 100%;
					height: 100%;

					image {
						width: 100%;
						height: 100%;
					}
				}
			}

			.mask {

				&>view {
					position: absolute;
					left: 0;
					right: 0;
					margin: auto;
					width: fit-content;
					color: #fff;
				}

				.back {
					width: 38px;
					height: 38px;
					background: rgba(0, 0, 0, 0.5);
					left: 30rpx;
					margin-left: 0;
					border-radius: 100px;
					top: 0;
					backdrop-filter: blur(10rpx);
					border: 1rpx solid rgba(255, 255, 255, 0.3);
					/* 居中操作 */
					display: flex;
					justify-content: space-around;
					align-items: center;
				}

				.count {
					top: 10vh;
					padding: 8rpx 28rpx;
					background-color: rgba(0, 0, 0, 0.3);
					border-radius: 14rpx;
					backdrop-filter: blur(10rpx);
					font-size: 28rpx;
					color: #fff;
				}

				.time {
					top: calc(10vh + 80rpx);
					font-size: 140rpx;
					font-weight: 100;
					line-height: 1em;
					text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
				}

				.date {
					top: calc(10vh + 230rpx);
					font-size: 40rpx;
					font-weight: 100;
					line-height: 1em;
					text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
				}

				.footer {
					bottom: 10vh;
					width: 65vw;
					height: 120rpx;
					background-color: rgba(255, 255, 255, 0.8);
					border-radius: 60rpx;
					backdrop-filter: blur(20rpx);
					box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
					color: #000;
					/* 居中操作 */
					display: flex;
					justify-content: space-around;
					align-items: center;

					.box {
						padding: 2rpx 12rpx;
						/* 居中操作 */
						display: flex;
						flex-direction: column;
						justify-content: space-around;
						align-items: center;

						.text {
							font-size: 26rpx;
							color: $text-font-color-2;
						}
					}
				}
			}

			.infoheader {
				display: flex;
				justify-content: space-between;
				align-items: center;

				.title {
					color: $text-font-color-2;
				}

				.close {
					padding: 6rpx;
				}
			}

			.infopopup {
				max-width: 750rpx;
				padding: 30rpx;
				background-color: #fff;
				border-radius: 30rpx 30rpx 0 0;
				overflow: hidden;

				scroll-view {
					// height: fit-content;
					max-height: 60vh;

					.content {
						/* 关键样式：内容区域占据剩余高度 */
						flex: 1;
						height: auto; // 重要：确保高度自适应
						overflow: hidden; // 防止溢出

						.row {
							display: flex;
							padding: 16rpx 0;
							font-size: 32rpx;
							line-height: 1.7em;

							.label {
								color: $text-font-color-3;
								font-size: 30rpx;
								width: 140rpx;
								text-align: right;
							}

							.value {
								padding-right: 30rpx;
								flex: 1;
								width: 0;
							}

							.rate {
								display: flex;
								align-items: center;

								.score {
									font-size: 26rpx;
									color: $text-font-color-3;
									padding-left: 10rpx;
								}
							}

							.tabs {
								display: flex;
								flex-wrap: wrap;

								.tab {
									border: 1px solid $brand-theme-color;
									color: $brand-theme-color;
									font-size: 22rpx;
									padding: 10rpx 30rpx;
									border-radius: 40rpx;
									line-height: 1em;
									margin: 0 10rpx 10rpx 0;
								}
							}

							.hightClass {
								color: $brand-theme-color;
							}
						}

						.copyright {
							font-size: 28rpx;
							padding: 20rpx 40rpx;
							background: #F6F6F6;
							color: #666;
							border-radius: 10rpx;
							margin: 20rpx 0;
							line-height: 1.6em;
						}
					}
				}
			}

			.scorePopup {
				width: 70vw;
				height: fit-content;
				background-color: #fff;
				border-radius: 30rpx;
				padding: 20rpx;

				.content {
					width: 100%;
					height: fit-content;
					padding: 20rpx 0;
					display: flex;
					justify-content: center;
					align-items: center;

					// background-color: aqua;
					.score {
						color: #ffca3e;
						padding-left: 10rpx;
						font-size: 30rpx;
						width: 80rpx;
						line-height: 1em;
						text-align: right;
					}
				}

				.footer {
					padding: 10rpx 0;
					display: flex;
					justify-content: center;
					align-items: center;
					// background-color: brown;
				}
			}
		}
	}
</style>